import axios from 'axios'
import qs from 'qs'
import { message, notification } from 'ant-design-vue'
import Loading from "@/components/LoadView/index"
import store from '@/store'
import { noTokenApiArray } from '@/config'
import { getTenantCode } from './utils'

//http request 拦截器--start
const isIE9 = () => {
    if (
        navigator.appName == "Microsoft Internet Explorer" &&
        parseInt(
            navigator.appVersion
                .split(";")[1]
                .replace(/[ ]/g, "")
                .replace("MSIE", "")
        ) <= 9
    ) {
        return true;
    }
    return false;
}

// axios.defaults.baseURL = 'http://10.1.254.42/api';
axios.defaults.baseURL = '/api';


axios.defaults.timeout = 10000;

let loadingNum = 0;
axios.interceptors.request.use(
    config => {
    // console.log(config,'request config')
    /*
    自定义配置说明 :
    requestType：formData/udm/默认     请求类型
    isGetFile: true/false   是否为请求文件，不带Authorization
    */
        switch(config.requestType){
        case 'formData':
            config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
            config.data = qs.stringify(config.data)
            break;
        case 'udm':
            config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
            break;
        default:
            config.headers['Content-Type'] = 'application/json'
            config.headers['x-requested-with'] = 'XMLHttpRequest'
            break;
        }

        let token = store.state.user.token;
        // console.log(token,'token')
        if (token){
            if(!config.isGetFile){
                config.headers.Authorization = `Bearer ${token}`;
            }
        }else{
            // 过滤不需要token 的接口
            if(!noTokenApiArray.includes(config.url)){
                // message.error('token丢失，请重新登录')
                // window.location.href = '/#/user/login'
                // throw new Error('token丢失')
            }

        }
        if (config.loading) {
            if (loadingNum == 0) { Loading.show(); }
            loadingNum++;
        }
        return config
    },
    error => {
        return Promise.reject(error);
    }
);


//http response 拦截器
axios.interceptors.response.use(
    response => {
    // console.log('返回配置对象',response.config)
        if (response?.config?.loading) {
            loadingNum--;
        }
        // console.log(loadingNum)
        if (loadingNum < 1) {
            loadingNum = 0;
            setTimeout(()=>{
                Loading.hide();
            })
        }
        //判断是否有是ie9
        if (isIE9()) {
            //特殊处理response
            if (response.status == 200 && response.request) {
                if (
                    response.request.responseType === "json" &&
                    response.request.responseText
                ) {
                    response.data = JSON.parse(response.request.responseText);
                }
            }
        }

        return response.data;
    },
    err => {
    // loading.close()
        loadingNum--;
        if (loadingNum < 1) {
            loadingNum = 0;
            setTimeout(()=>{
                Loading.hide();
            })
        }

        if (String(err).indexOf('timeout') !== -1) {
            notification.open({
                title: '提示',
                message: '请求超时',
                type: 'error',
                duration: 3
            })
            return
        }
        if (err && err.response) {
            switch (err.response.status) {
            case 400:
                err.message = '请求错误'
                break

            case 401:
                err.message = err.response.msg || '未授权，请登录'
                store.commit('user/set_userLogout')
                break

            case 403:
                err.message = '拒绝访问'
                break

            case 404:
                err.message = `请求地址出错: ${err.response.config.url}`
                break

            case 408:
                err.message = '请求超时'
                break

            case 500:
                err.message = '服务器内部错误'
                break

            case 501:
                err.message = '服务未实现'
                break

            case 502:
                err.message = '网关错误'
                break

            case 503:
                err.message = '服务不可用'
                break

            case 504:
                err.message = '网关超时'
                break

            case 505:
                err.message = 'HTTP版本不受支持'
                break
            default:
                err.message = `连接错误${err.response.status}`
            }

            if (err.response.status != 401) {
                notification.open({
                    title: '提示',
                    message: err.message,
                    type: 'error',
                    duration: 3
                })
            }
        }
        return Promise.reject(err) // 返回接口返回的错误信息
    }
)

/**
 * 封装get方法
 * @param url
 * @param params
 * @param isMock 是否开启mock模拟数据
 * @param loading 是否显示遮罩加载
 * @returns {Promise}
 */


export function get(url, params, option) {
    let options = {
        isMock: false,
        loading: false,
        ...option
    };
    return axios({
        url: url,
        method: 'get',
        params,
        ...options
    })
}

/**
 * 封装post方法
 * @param url
 * @param params
 * @param isMock 是否开启mock模拟数据
 * @param loading 是否显示遮罩加载
 * @returns {Promise}
 */

export function post(url, data, option) {
    let options = {
        isMock: false,
        loading: false,
        ...option
    };
    return axios.post(url, data, option)
}

/*
 *postQuery 请求方法
 * @param url
 * @param params
 * @returns {Promise}
 */
export function postQuery(url, query, data, option) {
    let options = {
        isMock: false,
        loading: false,
        ...option
    };
    return axios({
        url: url,
        method: 'post',
        params: {
            ...query
        },
        data: data,
        ...options
    })
}

/*
 *put 请求方法
 * @param url
 * @param params
 * @returns {Promise}
 */
export function put(url, query, data, option) {
    let options = {
        isMock: false,
        loading: false,
        ...option
    };
    return axios({
        url: url,
        method: 'put',
        params: {
            ...query
        },
        data: data,
        ...options
    })
}

/*
 *del 请求方法
 * @param url
 * @query query
 */
export function del(url, query, data, option) {
    return axios.delete(url, {
        params: query
    })
}

/**
 * 封装ALL请求(合拼请求)
 * @param Array [请求1,请求2]
 * @returns {Promise}
 */

export function all(arr) {
    return axios.all([...arr])
}
